package com.infore.statisticsAndAlarm.service.impl;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.infore.statisticsAndAlarm.constant.Constants;
import com.infore.statisticsAndAlarm.dto.WaterInstructionsDataDto;
import com.infore.statisticsAndAlarm.enums.ResultStatus;
import com.infore.statisticsAndAlarm.externalInterface.IDataReceivingService;
import com.infore.statisticsAndAlarm.externalInterface.IStieMangementService;
import com.infore.statisticsAndAlarm.outsideEntity.Project;
import com.infore.statisticsAndAlarm.service.IWaterQualityMapService;
import com.infore.statisticsAndAlarm.util.ArrayUtils;
import com.infore.statisticsAndAlarm.util.MyBeanUtils;
import com.infore.statisticsAndAlarm.util.ObjectMapperUtil;
import com.infore.statisticsAndAlarm.util.ReflexUtil;
import com.infore.statisticsAndAlarm.util.ResultEntity;
import com.infore.statisticsAndAlarm.util.ScaleUtil;
import com.infore.statisticsAndAlarm.util.StationRateUtil;
import com.infore.statisticsAndAlarm.util.WaterLevelUtils;
import com.infore.statisticsAndAlarm.util.WaterQualityUtil;
import com.infore.statisticsAndAlarm.vo.SdcjgyyProjectVo;
import com.infore.statisticsAndAlarm.vo.SdcjgyyWaterMapVo;

@Service
public class WaterQualityMapServiceImpl implements IWaterQualityMapService {

	@Autowired
	private IStieMangementService iStieMangementService;
	@Autowired
	private ObjectMapperUtil ObjectMapperUtil;
	@Autowired
	private IDataReceivingService iDataReceivingService;
	@Autowired
	private WaterLevelUtils WaterLevelUtils;
	@Value("${sdcjgyyAllMn}")
	private String allMn; //配置文件配置的物理保存地址


	/** 多站点多因子站点mn时间段--分组得到数据 **/
	public List<Map<String, Object>> datasCenterMore(String type, String startTime, String endTime, String stationMn) {
		List<Map<String, Object>> dataResult = new ArrayList<Map<String, Object>>();// 小时天月数据结果集
		// 查询单站点下因子code集合
		ResultEntity projectCodesEntity = iStieMangementService.queryProjectByStationMn(stationMn);
		List<String> projectCodes = ObjectMapperUtil.convertList(projectCodesEntity, String.class);// 站点下因子集合
		if (projectCodes == null || projectCodes.size() == 0) {
			return dataResult;
		}
		List<Map<String, Object>> dataResults = new ArrayList<Map<String, Object>>();
		if (projectCodes == null || StringUtils.isBlank(stationMn) || projectCodes.size() == 0) {
			return dataResults;
		}
		String codeString = StringUtils.join(projectCodes, ",");
		// 判断查询那钟类型的表----------如果小时分钟秒有对应的表在进行判断
//		if ("M".equals(type)) {// 分钟
//		} else if ("S".equals(type)) {// 秒
//		} else {// 查询小时表
//			ResultEntity resultEntity = iDataReceivingService.audioMoreReport(stationMn, codeString, startTime,
//					endTime);
//			if (resultEntity.getCode() != 0) {
//				return dataResults;
//			}
//			dataResults = ObjectMapperUtil.convertListMap(resultEntity);
//		}

		// 暂时按小时表来查
		// 查询小时表
		ResultEntity resultEntity = iDataReceivingService.audioMoreReport(stationMn, codeString, startTime, endTime);
		if (resultEntity.getCode() != 0) {
			return dataResults;
		}
		dataResults = ObjectMapperUtil.convertListMap(resultEntity);
		return dataResults;
	} 

	@SuppressWarnings("unchecked")
	public ResultEntity query(String startTime, String endTime, String stationMns) {
		ResultEntity stationResultEntity = iStieMangementService.queryInfoByMnSdcjgyy(allMn);// 查询站点
		List<Map<String, Object>> stationList = ObjectMapperUtil.convertListMap(stationResultEntity);// 得到站点基础信息
		List<Map<String, Object>> values = datasCenterMore("", startTime, endTime, allMn);// 得到小时数据
		Map<String, Object> rateMap = StationRateUtil.uploadRateReports(allMn, startTime, endTime, stationList,
				values);// 得到上传率和有效率
		// 得到所有因子编码
		List<String> mnList = ArrayUtils.stringToList(allMn);
		ResultEntity projectResultEntity = iStieMangementService.queryProjectByMn(mnList);
		List<Map<String, Object>> ststaionMaps = getProjectLevel(values, projectResultEntity);
		Map<String, Object> stationMap = new HashMap<String, Object>();
		for (Map<String, Object> map : ststaionMaps) {
			stationMap.put(map.get("mn").toString(), map);
		}
		List<SdcjgyyWaterMapVo> list = new ArrayList<SdcjgyyWaterMapVo>();
		int online = 0;
		for (Map<String, Object> station : stationList) {
			String stationName = station.get("STATIONNAME").toString();
			String stationMn = station.get("MN").toString();
			String targertLevel = station.get("ARMLEVEL").toString();
			Integer targertLevelNum = NumberUtils
					.createInteger(WaterLevelUtils.exchangeWaterLevelToNumber(targertLevel));
			Map<String, Object> rateSingleMap = (Map<String, Object>) rateMap.get(stationMn);
			SdcjgyyWaterMapVo sdcjgyyWaterMapVo = new SdcjgyyWaterMapVo();
			sdcjgyyWaterMapVo.setStationMn(stationMn);
			sdcjgyyWaterMapVo.setStationName(stationName);
			sdcjgyyWaterMapVo.setUploadRate(rateSingleMap.get("up_rate").toString());
			sdcjgyyWaterMapVo.setValidRate(rateSingleMap.get("enable_rate").toString());
			if (!"0.0%".equals(rateSingleMap.get("up_rate").toString())) {
				online++;
			}
			Map<String, Object> map = (Map<String, Object>) stationMap.get(stationMn);
			if (map != null) {
				String stationLevel = map.get("level") == null ? "" : map.get("level").toString();
				String waterCondition = map.get("waterCondition") == null ? "" : map.get("waterCondition").toString();
				sdcjgyyWaterMapVo.setStationLevel(stationLevel);
				sdcjgyyWaterMapVo.setWaterCondition(waterCondition);
				List<SdcjgyyProjectVo> sdc = (List<SdcjgyyProjectVo>) map.get("sdc");
				// 计算因子达标率
				Double sum = 0D;
				Integer low = 0;
				for (SdcjgyyProjectVo sdcjgyy : sdc) {
					if (StringUtils.isNotBlank(sdcjgyy.getProjectLevel())) {
						Integer numLevel = sdcjgyy.getLevel();
						if (numLevel <= targertLevelNum) {
							low++;
						}
						sum++;
					}
				}
				double lowRate = low / sum;
				if (lowRate > 1) {
					lowRate = 1;
				}
				String rateString = getRateFormate(lowRate);
				sdcjgyyWaterMapVo.setProjectReachStandard(rateString);
				sdcjgyyWaterMapVo.setSdcjgyyProjectVos(sdc);
			}
			if (StringUtils.isNotBlank(stationMns) && stationMns.contains(stationMn)) {
				list.add(sdcjgyyWaterMapVo);
			}
			if (StringUtils.isBlank(stationMns)) {
				list.add(sdcjgyyWaterMapVo);
			}
		}
		int allNum = ArrayUtils.stringToList(allMn).size();
		double rateSystem = online / (allNum * 1.0D);
		if (rateSystem > 1) {
			rateSystem = 1;
		}
		String sysRate = getRateFormate(rateSystem);
		return new ResultEntity(ResultStatus.SUCCESS,Constants.QUERY_SUCCESS).setDataList(list)
				.setMapValue("sysRate", sysRate);
	}

	String getRateFormate(Double rate) {
		NumberFormat nt = NumberFormat.getPercentInstance();
		// 设置百分数保留两位小数
		nt.setMinimumFractionDigits(2);
		String rateString = nt.format(rate);
		return rateString;
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> getProjectLevel(List<Map<String, Object>> dataResult,
			ResultEntity projectResultEntity) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();// 结果集
		// 查询因子值数据集
		Map<String, Object> resultMap = new HashMap<String, Object>();// 存储每一条数据
		Map<String, Object> valueMap = new HashMap<String, Object>();// 水质等级计算，存储记录类
		List<WaterInstructionsDataDto> InstructionsList = new ArrayList<WaterInstructionsDataDto>();
		// 获得因子信息
		Map<String, Project> projectMap = null;
		if (projectResultEntity.getCode() == 0) {
			projectMap = (Map<String, Project>) ((Map<String, Project>) projectResultEntity.getContent()).get("info");
		}
		// 遍历因子值数据集，设置相关的值
		for (Map<String, Object> dataResultMap : dataResult) {
			String mn = dataResultMap.get("MN").toString();
			String projectCode = dataResultMap.get("CODE").toString();
			String value = dataResultMap.get("VALUE").toString();
			String projectName = "";
			String decimalDigits = "3";
			if (projectMap != null) {
				Project project = MyBeanUtils.convertMapToBean((Map<String, Object>) projectMap.get(projectCode),
						Project.class);
				projectName = project.getProjectName();
				decimalDigits = project.getDecimalDigits();
			}
			value = ScaleUtil.sciCalProjectString(value, decimalDigits);// 数据修约
			// 如果当前站点下没有因子相关信息，则创建新的，否则在原有的上追加
			if (!valueMap.containsKey(mn)) {
				List<SdcjgyyProjectVo> sdc = new ArrayList<SdcjgyyProjectVo>();
				SdcjgyyProjectVo sdcjgyyProjectVo = new SdcjgyyProjectVo();
				resultMap = new HashMap<String, Object>();
				WaterInstructionsDataDto Instructions = new WaterInstructionsDataDto();// 计算水质等级封装类
				ReflexUtil.setValue(Instructions, WaterInstructionsDataDto.class, projectCode, String.class, value);
				InstructionsList.add(Instructions);
				WaterQualityUtil.setWaterQuality(InstructionsList);
				String waterQuery = WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
				resultMap.put("mn", mn);// 站点mn
				sdcjgyyProjectVo.setLevel(WaterQualityUtil.getWaterLevel(projectCode, value));// 因子编号和因子值
				sdcjgyyProjectVo.setProjectValue(value);// 因子编号和因子值
				sdcjgyyProjectVo.setProjectName(projectName);// 因子编号和因子值
				sdcjgyyProjectVo.setProjectCode(projectCode);
				sdcjgyyProjectVo.setProjectLevel(WaterLevelUtils
						.exchangeWaterLevelToChinese(WaterQualityUtil.getWaterLevel(projectCode, value) + ""));// 因子编号和因子值
				resultMap.put("level", waterQuery);// 站点水质等级
				resultMap.put("waterCondition", WaterLevelUtils.calculateProject(waterQuery));// 水质状况（优良轻度污染等）
				valueMap.put(mn, Instructions);
				valueMap.put(mn + "pro", sdc);
				sdc.add(sdcjgyyProjectVo);
				resultMap.put("sdc", sdc);
				list.add(resultMap);
			} else {
				List<SdcjgyyProjectVo> sdc = (List<SdcjgyyProjectVo>) valueMap.get(mn + "pro");
				SdcjgyyProjectVo sdcjgyyProjectVo = new SdcjgyyProjectVo();
				WaterInstructionsDataDto Instructions = (WaterInstructionsDataDto) valueMap.get(mn);
				ReflexUtil.setValue(Instructions, WaterInstructionsDataDto.class, projectCode, String.class, value);
				WaterQualityUtil.setWaterQuality(InstructionsList);
				String waterQuery = WaterLevelUtils.exchangeWaterLevelToChinese(Instructions.getWaterQuality());
				resultMap.put("level", waterQuery);
				resultMap.put("waterCondition", WaterLevelUtils.calculateProject(waterQuery));
				sdcjgyyProjectVo.setLevel(WaterQualityUtil.getWaterLevel(projectCode, value));// 因子编号和因子值
				sdcjgyyProjectVo.setProjectValue(value);// 因子编号和因子值
				sdcjgyyProjectVo.setProjectName(projectName);// 因子编号和因子值
				sdcjgyyProjectVo.setProjectCode(projectCode);
				sdcjgyyProjectVo.setProjectLevel(WaterLevelUtils
						.exchangeWaterLevelToChinese(WaterQualityUtil.getWaterLevel(projectCode, value) + ""));// 因子编号和因子值
				sdc.add(sdcjgyyProjectVo);
				resultMap.put("sdc", sdc);
				valueMap.put(mn + "pro", sdc);
			}
		}
		return list;
	}

}
